<template>
	<div class="role-management">
		<div class="header">
			<h2>角色管理</h2>
			<el-button type="primary" @click="showDialog">新增角色</el-button>
		</div>

		<!-- 搜索表单 -->
		<el-form :model="searchForm" inline>
			<el-form-item label="角色名称">
				<el-input v-model="searchForm.role_name" placeholder="请输入角色名称" clearable />
			</el-form-item>
			<el-form-item label="状态">
				<el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
					<el-option label="启用" :value="1" />
					<el-option label="禁用" :value="0" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleSearch">搜索</el-button>
				<el-button @click="resetSearch">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 角色表格 -->
		<el-table :data="tableData" border style="width: 100%" v-loading="loading">
			<el-table-column prop="roleId" label="角色ID" width="100" />
			<el-table-column prop="roleName" label="角色名称" width="150" />
			<el-table-column prop="roleCode" label="角色代码" width="150" />
			<el-table-column prop="roleDesc" label="角色描述" />
			<el-table-column prop="status" label="状态" width="100">
				<template #default="scope">
					<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
						{{ scope.row.status === 1 ? '启用' : '禁用' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" width="180" />
			<el-table-column prop="updateTime" label="更新时间" width="180" />
			<el-table-column label="操作" width="310" fixed="right">
				<template #default="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
					<el-button size="small" @click="menusEdit(scope.row)">菜单维护</el-button>
					<el-button size="small" @click="roleshareEdit(scope.row)">角色分配</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="pagination">
			<el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
				:total="pagination.total" :page-sizes="[10, 20, 50, 100]"
				layout="total, sizes, prev, pager, next, jumper" @size-change="fetchData" @current-change="fetchData" />
		</div>

		<!-- 新增/编辑对话框 -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="resetForm">
			<el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
				<el-form-item label="角色名称" prop="role_name">
					<el-input v-model="form.role_name" placeholder="请输入角色名称" />
				</el-form-item>

				<el-form-item label="角色代码" prop="role_code">
					<el-input v-model="form.role_code" placeholder="请输入角色代码" />
				</el-form-item>

				<el-form-item label="角色描述" prop="role_desc">
					<el-input v-model="form.role_desc" type="textarea" placeholder="请输入角色描述" :rows="3" />
				</el-form-item>

				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="form.status">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<el-drawer v-model="drawer" title="I am the title" :with-header="false">
			<span>[角色名字:{{rolename}}]菜单维护<el-button size="small" @click="subuprolemenus()">确定修改角色菜单</el-button>
			</span>
			<el-tree ref="treeRef" style="max-width: 600px" :data="menutreedata" show-checkbox node-key="menuId"
				:default-expand-all="true" :default-checked-keys="defaultmenusid" :props="defaultProps"
				:check-strictly="true" />
		</el-drawer>

		<el-drawer v-model="drawer2" title="I am the title" :with-header="false">
			<span>[{{rolename}}]角色分配
				<el-button type="primary" @click="subuproleuser">确定修改</el-button>
			</span>

			<div class="m-4">
				<p>所属人员</p>
				<el-cascader style="width: 100%;" v-model="roleusers" placeholder="请选择人员" :options="optionsuser"
					:props="propsuser" filterable />

				<p>所属部门</p>
				<el-cascader style="width: 100%;" v-model="roledepartments" placeholder="请选择部门"
					:options="optionsdepartments" :props="propsdepartments" filterable />
			</div>
		</el-drawer>

	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import request from '../utils/request'

	// 表格数据
	const tableData = ref([]);
	const loading = ref(false);
	const drawer = ref(false); //控制角色菜单的抽屉
	const roleid = ref() //当前操作的角色id
	const rolename = ref() //当前操作角色id对应的角色名字
	const treeRef = ref() //ref方式引用树
	const drawer2 = ref(false) //控制角色分配的抽屉
	const roleusers = ref(); //角色对应的用户id集合
	const roledepartments = ref() //角色对应的部门id集合

	const propsuser = ref({
		multiple: true,
		"value": "userId",
		"label": "realName"
	})
	const propsdepartments = ref({
		multiple: true,
		"value": "deptId",
		"label": "deptName"
	})

	const optionsuser = ref([{
		value: 'guide',
		label: '显示值',
		children: []
	}]) //所有的用户集合

	const optionsdepartments = ref([]) //所有的部门集合

	const defaultProps = ref({
		children: 'children',
		label: 'menuName',
	}) //设置树的属性
	const menutreedata = ref([{
		id: 1,
		label: 'Level one 1',
		children: [{
			id: 4,
			label: 'Level two 1-1',
		}],
	}]) //菜单树的数据
	const defaultmenusid = ref([]) //设置菜单树默认选中的

	// 分页配置
	const pagination = reactive({
		current: 1,
		size: 10,
		total: 0
	});

	// 搜索表单
	const searchForm = reactive({
		role_name: '',
		status: null
	});

	// 对话框控制
	const dialogVisible = ref(false);
	const dialogTitle = ref('新增角色');
	const isEdit = ref(false);
	const currentId = ref(null);

	// 表单数据和验证规则
	const formRef = ref(null);
	const form = reactive({
		role_name: '',
		role_code: '',
		role_desc: '',
		status: 1
	});

	const rules = {
		role_name: [{
				required: true,
				message: '请输入角色名称',
				trigger: 'blur'
			},
			{
				min: 2,
				max: 20,
				message: '长度在 2 到 20 个字符',
				trigger: 'blur'
			}
		],
		role_code: [{
				required: true,
				message: '请输入角色代码',
				trigger: 'blur'
			},
			{
				pattern: /^[a-zA-Z0-9_]+$/,
				message: '只能包含字母、数字和下划线',
				trigger: 'blur'
			}
		],
		status: [{
			required: true,
			message: '请选择状态',
			trigger: 'change'
		}]
	};

	// 生命周期钩子
	onMounted(() => {
		fetchData();
	});

	// 获取数据
	const fetchData = async () => {
		try {
			loading.value = true;
			request.get("/roles/page").then(function(res) {
				tableData.value = res.data

			}).catch(function(res) {

			})

			pagination.total = 2;
		} catch (error) {
			ElMessage.error('获取数据失败');
		} finally {
			loading.value = false;
		}
	};

	// 搜索
	const handleSearch = () => {
		pagination.current = 1;
		fetchData();
	};

	// 重置搜索
	const resetSearch = () => {
		searchForm.role_name = '';
		searchForm.status = null;
		handleSearch();
	};

	// 显示对话框
	const showDialog = () => {
		dialogTitle.value = '新增角色';
		isEdit.value = false;
		dialogVisible.value = true;
	};


	//获取所有的菜单，菜单树
	const getAllMenus = (row) => {
		request.get("/menus/list").then(function(res) {
			let treestr = arrayToTree(res.data, "menuId", "parentId")
			menutreedata.value = treestr
		}).catch(function(res) {

		})
	}

	//获取角色对应的菜单集合
	const getRoleMenusId = (row) => {
		request.get("/menus/listbyroleid/" + row.roleId).then(function(res) {
			defaultmenusid.value = res.data
		}).catch(function(res) {

		})
	}

	//角色对应的菜单分配
	const menusEdit = (row) => {
		//设置当前操作的角色id
		roleid.value = row.roleId
		rolename.value = row.roleName

		drawer.value = true
		defaultmenusid.value = [] //清除原有的
		getAllMenus(row) //设置所有的菜单树数据
		getRoleMenusId(row) //获取角色拥有的菜单id集合
	};

	//根据角色id修改菜单集合
	const subuprolemenus = () => {
		let menudids = treeRef.value.getCheckedKeys(); //选中的菜单id集合
		request.post("/menus/uprolemenusbyroleid", {
			roleid: roleid.value,
			menudids: menudids
		}).then(function(res) {
			ElMessage({
				message: "操作成功",
				type: 'success',
				duration: 5 * 1000
			})
			drawer.value = false
		}).catch(function(res) {

		})

	}

	//确定修改角色对应的用户及部门
	const subuproleuser = () => {
		request.post("/user_role/uproleuserid", {
			"roleid": roleid.value, //角色id数值
			"usersid": roleusers.value.flat(), //用户id集合
			"departmentsid": roledepartments.value.flat() //部门id集合
		}).then(function(res) {
			ElMessage({
				message: "操作成功",
				type: 'success',
				duration: 5 * 1000
			})
			drawer2.value = false
		}).catch(function(res) {

		})
		// alert(roleusers.value + "===" + roleid.value + "==" + roledepartments.value)
	}

	//获取所有的部门集合
	const initdepartments = () => {
		request.get("/departments/getalldepartments").then(function(res) {
			optionsdepartments.value = res.departments
			// console.log(optionsdepartments.value)
		}).catch(function(res) {

		})
	}

	//获取所有的用户集合
	const initusers = () => {
		request.get("/users/getalluser").then(function(res) {
			optionsuser.value = res.users
			// console.log(res.users)
		}).catch(function(res) {

		})
	}

	//角色分配人员及部门
	const roleshareEdit = (row) => {
		roleusers.value = []
		roledepartments.value = []
		//设置当前操作的角色id
		roleid.value = row.roleId
		rolename.value = row.roleName

		drawer2.value = true
		initusers() //获取所有的用户信息
		initdepartments() //获取所有的部门信息
		//获取当前角色对应的用户及部门
		getroleUserDepartmentsById(row.roleId)
	}
	const getroleUserDepartmentsById = (roleid) => {
		request.get("/user_role/getroluUserdepartmentsbyid/" + roleid).then(function(res) {

			const allUserIds = res.list.map(item => item.userId)
			for (let i = 0; i < allUserIds.length; i++) {
				console.log(allUserIds[i])
				if (allUserIds[i].startsWith("{")) { //属于部门id
					// console.log("部门id" + allUserIds[i].match(/\d+/)[0])
					roledepartments.value.push(parseInt(allUserIds[i].match(/\d+/)[0]))
				} else if (allUserIds[i].startsWith("(")) { //属于用户id
					let a = parseInt(allUserIds[i].match(/\d+/)[0])
					roleusers.value.push(a)
					// roleusers.value.push(1)
					// roleusers.value.push(2)
				}
			}

		}).catch(function(res) {

		})
	}

	// 编辑
	const handleEdit = (row) => {
		dialogTitle.value = '编辑角色';
		isEdit.value = true;
		currentId.value = row.role_id;
		Object.assign(form, row);
		dialogVisible.value = true;
	};

	// 删除
	const handleDelete = (row) => {
		ElMessageBox.confirm('确定要删除该角色吗?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
			try {
				// 这里替换为实际的API调用
				// await api.deleteRole(row.role_id);
				ElMessage.success('删除成功');
				fetchData();
			} catch (error) {
				ElMessage.error('删除失败');
			}
		}).catch(() => {});
	};

	// 提交表单
	const submitForm = () => {
		formRef.value.validate(async (valid) => {
			if (valid) {
				try {
					// 这里替换为实际的API调用
					// if (isEdit.value) {
					//   await api.updateRole(currentId.value, form);
					// } else {
					//   await api.addRole(form);
					// }

					ElMessage.success(isEdit.value ? '修改成功' : '添加成功');
					dialogVisible.value = false;
					fetchData();
				} catch (error) {
					ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
				}
			}
		});
	};

	// 重置表单
	const resetForm = () => {
		formRef.value?.resetFields();
		Object.assign(form, {
			role_name: '',
			role_code: '',
			role_desc: '',
			status: 1
		});
		currentId.value = null;
	};

	function arrayToTree(items, id = 'id', parentId = 'parentId', children = 'children') {
		const result = [];
		const map = new Map();

		// 构建映射
		items.forEach(item => {
			map.set(item[id], {
				...item,
				[children]: []
			});
		});

		// 构建树
		items.forEach(item => {
			const parent = map.get(item[parentId]);
			if (parent) {
				parent[children].push(map.get(item[id]));
			} else {
				result.push(map.get(item[id]));
			}
		});

		return result;
	}
</script>

<style scoped>
	.role-management {
		padding: 20px;
		background-color: #fff;
		border-radius: 4px;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.pagination {
		margin-top: 20px;
		display: flex;
		justify-content: flex-end;
	}
</style>